﻿module game.battle.radar;

import gamelib.types;
import gamelib.graphics.renderer2d.renderer;

import game.units;

final class Radar
{
private:
    immutable Rect mViewport;
    immutable Point mViewCenter;
    Point[] mPoints;

public:
    this(in Rect viewport) pure nothrow
    {
        mViewport = viewport;
        mViewCenter = Point(mViewport.x + mViewport.w / 2, mViewport.y + mViewport.h / 2);
    }

    void draw(T)(Renderer ren, in scalar_t range, in pos_t viewPos,  in rot_t viewDir, T entityContainer)
    {
        if(entityContainer.empty)
        {
            return;
        }

        if(entityContainer.length > mPoints.length)
        {
            mPoints.length = calcCacheSize(entityContainer.length);
        }
        auto mat = toRotMat(viewDir).transposed;
        auto rangeSq = (cast(scalarw_t)range) ^^ 2;
        auto coeff = min(mViewport.w, mViewport.h) / range;

        int i = 0;
        foreach(e;entityContainer)
        {
            auto relPos = e.pos - viewPos;
            if(relPos.magnitude_squared > rangeSq)
            {
                continue;
            }
            relPos = mat * relPos;
            relPos = relPos * coeff;
            mPoints[i] = Point(mViewCenter.x - cast(int)relPos.y, mViewCenter.y - cast(int)relPos.x);
            ++i;
        }

        ren.drawPoints(mPoints[0..i]);
    }
}

